package com.mineplatform.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.net.URL;
import javax.net.ssl.HttpsURLConnection;
import com.fasterxml.jackson.databind.ObjectMapper;

public class IMUtil {
	public static final String BASE_URL = "https://a1.easemob.com/eddyzhang1986/mineplatform/";
	public static final String USERS_URL = BASE_URL + "users";

	public static String registUser(String username, String password) throws IOException {

		IMUser user = new IMUser();
		user.setUsername(username);
		user.setPassword(password);

		ObjectMapper mapper = new ObjectMapper();
		String json = mapper.writeValueAsString(user);
		System.out.println(json);

		String result = post(USERS_URL, json);

		return result;

	}

	public static String post(String url, String payload) throws IOException {

		URL myurl = new URL(url);
		HttpsURLConnection con = (HttpsURLConnection) myurl.openConnection();

		con.setRequestMethod("POST");
		con.setRequestProperty("Content-type", "application/json");
		con.setRequestProperty("Accept-Charset", "utf-8");
		con.setRequestProperty("contentType", "utf-8");
		con.setDoOutput(true);

		OutputStream ous = con.getOutputStream();
		OutputStreamWriter out = new OutputStreamWriter(ous, "utf-8");
		out.write(payload);

		out.close();

		InputStream ins = con.getInputStream();
		InputStreamReader isr = new InputStreamReader(ins, "utf-8");
		BufferedReader in = new BufferedReader(isr);

		String inputLine;

		while ((inputLine = in.readLine()) != null) {
			System.out.println(inputLine);
		}

		in.close();

		return inputLine;

	}

}
